package com.dabai.sas.activitys;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.afollestad.materialdialogs.MaterialDialog;
import com.dabai.sas.R;
import com.dabai.sas.utils.DabaiUtils;
import com.dabai.sas.utils.FileUtil;
import com.dabai.sas.utils.UriUtils;
import com.dabai.utils.DateUtils;
import com.dabai.utils.DownloadUtils;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.util.FitPolicy;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static android.os.Environment.DIRECTORY_PICTURES;


public class PdfReaderActivity extends AppCompatActivity {

    Context context;
    String TAG = "DABAI";
    Uri uri;
    PDFView pdfView;
    private int  defaultPage=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf_reader);

        context = getApplicationContext();
        pdfView = findViewById(R.id.pdfView);

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            DabaiUtils.showToast(context, "请点击申请'储存权限'!");
            startActivity(new Intent(this, PermissionsActivity.class));
            finish();
            return;
        }


        try {
            init();
        } catch (Exception e) {
            DabaiUtils.showToast(this,"PDF打开失败!");
            finish();
        }
    }

    private void init() {

        //拿到uri
        uri = getIntent().getData();

        if (uri.toString().startsWith("file:///")) {
            File file = new File(FileUtil.getFileAbsolutePath(this, uri));
            pdfView.fromFile(file).defaultPage(defaultPage).load();
            Objects.requireNonNull(getSupportActionBar()).setTitle(file.getName());
        } else {
            pdfView.fromUri(uri).defaultPage(defaultPage).load();
            UriUtils file = new UriUtils(context, uri);
            Objects.requireNonNull(getSupportActionBar()).setTitle(file.getFileName());
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.share:
                DabaiUtils.sendFileWithUri(this, uri, "application/pdf");
                return true;
            case R.id.pdf_first:
                pdfToPage(1);
                return true;
            case R.id.pad_end:
                pdfToPage(pdfView.getPageCount());
                return true;
            case R.id.page_jump:

                new MaterialDialog.Builder(this)
                        .title("页数跳转")
                        .content("当前页:"+(pdfView.getCurrentPage()+1)+"/总页数:"+pdfView.getPageCount())
                        .positiveText("跳转")
                        .inputRangeRes(1, pdfView.getPageCount(), R.color.purple_700)
                        .inputType(InputType.TYPE_CLASS_NUMBER)
                        .input("想要跳转的页数","", (dialog, input) -> {

                        })
                        .onPositive((dialog, which) -> {
                            try {
                                assert dialog.getInputEditText() != null;

                              pdfToPage(Integer.parseInt(dialog.getInputEditText().getText().toString()));

                            } catch (Exception e) {
                                DabaiUtils.showToast(context, "跳转失败!");
                            }
                        })
                        .neutralText("取消")
                        .show();

                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void pdfToPage(int page){
        defaultPage = page - 1;
        if (uri.toString().startsWith("file:///")) {
            File file = new File(FileUtil.getFileAbsolutePath(this, uri));
            pdfView.fromFile(file).defaultPage(defaultPage).load();
            getSupportActionBar().setTitle(file.getName());
        } else {
            pdfView.fromUri(uri).defaultPage(defaultPage).load();
            UriUtils file = new UriUtils(context, uri);
            getSupportActionBar().setTitle(file.getFileName());
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.pdf_reader_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }


}